#!/usr/bin/env python
import numpy as np
import itk
import scipy.ndimage as ndi
import imageTools.ITKUtils.view as view
import imageTools.browse.a3d as a3d
import imageTools.ITKUtils.io as io
import sys
import os


def bone_extract(fname, low_th, high_th):

    reader = itk.ImageFileReader.ISS3.New()
    reader.SetFileName(fname)
    reader.Update()
    btf = itk.BinaryThresholdImageFilter.ISS3ISS3.New()
    btf.SetInput(reader.GetOutput())
    btf.SetLowerThreshold(low_th)
    btf.SetUpperThreshold(high_th)
    ccf = itk.ConnectedComponentImageFilter.ISS3IUL3.New()
    ccf.SetInput(btf.GetOutput())
    rcf = itk.RelabelComponentImageFilter.IUL3ISS3.New()
    rcf.SetInput(ccf.GetOutput())
    btf2 = itk.BinaryThresholdImageFilter.ISS3IUC3.New()
    btf2.SetInput(rcf.GetOutput())
    btf2.SetLowerThreshold(1)
    btf2.SetUpperThreshold(1)
    writer = itk.ImageFileWriter.IUC3.New()
    filename = "bone.mha"
    writer.SetFileName(filename)
    writer.SetInput(btf2.GetOutput())
    writer.Update()
    return filename
 
def count(fname):
   img = io.readImage(fname)
   arr = itk.PyBuffer.IF3.GetArrayFromImage(img)
   idx = np.where(arr>0)
   return len(idx[0])

def main():
   low_th = 0.5
   high_th =1 
   while True:  
      bone_extract(sys.argv[1], low_th, high_th)
      counter = count("bone.mha")
      print low_th, high_th,counter
      if (counter > 2500000) :
          low_th = low_th + 20 
      elif (counter < 1000000):
          low_th = low_th -10  
    
      else: 
          break 
   
if  __name__ == '__main__':
    main()
